package com.mk.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mk.base.exception.ApplicationException;
import com.mk.base.exception.StatusCode;
import com.mk.base.service.impl.BaseService;
import com.mk.common.*;
import com.mk.log.annotation.Log;
import com.mk.mapper.PacMapper;
import com.mk.model.entity.Pac;
import com.mk.model.entity.Tag;
import com.mk.model.request.PacRequest;
import com.mk.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @Author: yq
 * @Description:
 * @Date: Created in 2:31 PM 3/15/18
 */
@Service
public class PacService extends BaseService<PacMapper,Pac> implements IPacService {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private ITagService tagService;
    @Autowired
    private IFileInfoService fileInfoService;
    @Autowired
    private IUserService userService;

    @Value("${location.imageupload.path}")
    private String IMAGE_UPLOAD_PATH;

    @Override
    @Transactional
    @Log(module = "文档包管理",description = "创建文档包")
    public Pac savePac(PacRequest request) {
        if(ObjectUtils.isEmpty(request) || ObjectUtils.isEmpty(request.getTagRequest()))
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"创建文件包失败");
        String num = request.getTagRequest().getNum();
        if(StringUtils.isEmpty(num))
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"创建文件包时编号不可为空");
        Pac existByNum = getByTagNum(num);
        if(existByNum != null)
            throw new ApplicationException(StatusCode.UNIQUE_KE.getCode(),"创建文件包时编号不可重复");
        if(!StringUtils.isEmpty(request.getTagRequest().getLogo())){
            String url = FileUploadUtil.uploadFile(request.getTagRequest().getLogo(),IMAGE_UPLOAD_PATH);
            request.getTagRequest().setAvator(url);
        }else
            request.getTagRequest().setAvator(FileConfig.PAC_DEFAULT_IMAGE);
        Pac pac = BeanCopier.copy(request,Pac.class);
        if(StringUtils.isEmpty(pac.getTitle()))
            pac.setTitle(request.getTagRequest().getTitle());
        Date nowDate = new Date();
        pac.setCreateTime(nowDate);
        pac.setUpdateTime(nowDate);
        if(super.insert(pac)){
            request.getTagRequest().setLogo(null);
            request.getTagRequest().setPacId(pac.getId());
            Tag tag = tagService.saveTag(request.getTagRequest());
            if(tag != null){
                pac.setTag(tag);
            }
            return pac;
        }else
            throw new ApplicationException(StatusCode.CONFLICT.getCode(),"添加文件包信息失败");
    }

    @Override
    @Transactional
    @Log(module = "文档包管理",description = "编辑文档包信息")
    public Boolean updatePac(PacRequest request) {
        if(ObjectUtils.isEmpty(request) || ObjectUtils.isEmpty(request.getTagRequest())
                || request.getId() == null || request.getTagRequest().getId() == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"请传入文件包信息来编辑");
        String num = request.getTagRequest().getNum();
        if(!StringUtils.isEmpty(num)){
            Pac pac = getByTagNum(num);
            if(pac != null && !pac.getId().equals(request.getId()))
                throw new ApplicationException(StatusCode.UNIQUE_KE.getCode(),"文件包的编号不可重复");
        }
        if(StringUtils.isEmpty(request.getTitle()) && !StringUtils.isEmpty(request.getTagRequest().getTitle())){
            request.setTitle(request.getTagRequest().getTitle());
        }
        if(request.getTagRequest().getLogo() != null){
            Tag tag = tagService.get(request.getTagRequest().getId());
            //先删除以前的图片
            if(tag != null && !StringUtils.isEmpty(tag.getAvator())
                    && !FileConfig.PAC_DEFAULT_IMAGE.equals(tag.getAvator()))
                FileUploadUtil.deleteImage(IMAGE_UPLOAD_PATH + tag.getAvator());
            String url = FileUploadUtil.uploadFile(request.getTagRequest().getLogo(),IMAGE_UPLOAD_PATH);
            request.getTagRequest().setAvator(url);
            request.getTagRequest().setLogo(null);//不然报错
        }
        Pac pac = BeanCopier.copy(request,Pac.class);
        pac.setUpdateTime(new Date());
        if(super.updateById(pac)) {
            return tagService.updateTag(request.getTagRequest());
        }
        throw new ApplicationException(StatusCode.CONFLICT.getCode(),"编辑文件包信息失败");
    }

    @Override
    @Transactional
    @Log(module = "文档包管理",description = "删除单个文档包信息")
    public Boolean deletePac(Long id) {
        if(id == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"请选择需要删除的文档包");
        Pac exist = get(id);
        if(exist == null)
            throw new ApplicationException(StatusCode.CONFLICT.getCode(),"删除的文档包不存在");
        exist.setUpdateTime(new Date());
        exist.setIsDeleted(Config.ABLE_CONFIG.UNABLE);
        if(super.updateById(exist)) {
            if (tagService.deleteByPacId(id))//删除文档包以及下面的文件
                return fileInfoService.delAllFilesByPacId(exist.getDirId(), id);
        }
        throw new ApplicationException(StatusCode.CONFLICT.getCode(),"删除文档包信息失败");
    }

    @Override
    @Transactional
    @Log(module = "文档包管理",description = "添加文档包信息")
    public Pac saveOnlyOne(PacRequest request) {
        Pac pac = BeanCopier.copy(request,Pac.class);
        Date nowDate = new Date();
        pac.setCreateTime(nowDate);
        pac.setUpdateTime(nowDate);
        if(super.insert(pac))
            return pac;
        else
            throw new ApplicationException(StatusCode.CONFLICT.getCode(),"添加文档包信息失败");
    }

    @Override
    @Transactional
    @Log(module = "文档包管理",description = "删除文件夹下的所有资料包")
    public Boolean deletePacsByDirId(Long dirId) {
        return null;
    }

    @Override
    @Transactional
    @Log(module = "文档包管理",description = "移动文档包")
    public Boolean movePac(PacRequest request) {
        if(request == null || request.getId() == null || request.getDirId() == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"请传入需要移动的文档包以及文件夹信息");
        Pac exist = get(request.getId());
        if(exist == null)
            throw new ApplicationException(StatusCode.CONFLICT.getCode(),"移动的文档包信息不存在");
        exist.setDirId(request.getDirId());
        exist.setUpdateTime(new Date());
        return super.updateById(exist);
    }

    @Override
    @Log(module = "文档包管理",description = "查看文档包信息")
    public Pac get(Long id) {
        Pac pac = super.selectById(id);
        if(pac != null){
            pac.setTag(tagService.getByPacId(id));
        }
        return pac;
    }

    @Override
    public List<Pac> getByDirId(Long dirId) {
        List<Pac> pacs =  super.selectList(new EntityWrapper<Pac>()
                .eq("dir_id",dirId)
                .eq(Config.ABLE_CONFIG.ABLE_COLUMN,Config.ABLE_CONFIG.ABLE)
                .orderBy("create_time",false));
        if(!CollectionUtils.isEmpty(pacs)){
            for (Pac pac : pacs) {
                if(pac.getUserId() != null){
                    pac.setUsername(userService.get(pac.getUserId()).getUsername());
                }
                pac.setTag(tagService.getByPacId(pac.getId()));
            }
        }
        return pacs;
    }

    @Override
    public Pac getByTagNum(String num) {
        Pac pac = baseMapper.findByTagNum(num,Config.ABLE_CONFIG.ABLE);
        if(pac != null){
            pac.setTag(tagService.getByPacId(pac.getId()));
        }
        return pac;
    }

    @Override
    public List<Pac> keySearch(String key) {
        return baseMapper.keySearch(key,Config.ABLE_CONFIG.ABLE);
    }
}
